﻿<template>
  <div class="deviceSlaveTemplatePoints-container">
    <el-card shadow="hover" :body-style="{ paddingBottom: '0' }">
      <el-form :model="queryParams" ref="queryForm" labelWidth="90">
        <el-row>
          <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="4" class="mb10">
            <el-form-item label="关键字">
              <el-input v-model="queryParams.searchKey" clearable="" placeholder="请输入模糊查询关键字" />

            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="4" class="mb10" v-if="showAdvanceQueryUI">
            <el-form-item label="从机模板Id">
              <el-select clearable="" filterable="" v-model="queryParams.deviceSlaveTemplateId"
                placeholder="请选择设备从机模板Id">
                <el-option v-for="(item, index) in deviceSlaveTemplateDeviceSlaveTemplateIdDropdownList" :key="index"
                  :value="item.value" :label="item.label" />

              </el-select>

            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="4" class="mb10" v-if="showAdvanceQueryUI">
            <el-form-item label="数据类型">
              <el-select clearable="" v-model="queryParams.dataType" placeholder="请选择数据类型">
                <el-option v-for="(item, index) in dl('DataType')" :key="index" :value="item.value"
                  :label="`${item.name} (${item.code}) [${item.value}] `" />

              </el-select>

            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="4" class="mb10" v-if="showAdvanceQueryUI">
            <el-form-item label="长度">
              <el-input v-model="queryParams.len" clearable="" placeholder="请输入长度" />

            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="4" class="mb10" v-if="showAdvanceQueryUI">
            <el-form-item label="寄存器类型">
              <el-select clearable="" v-model="queryParams.regType" placeholder="请选择寄存器类型">
                <el-option v-for="(item, index) in dl('RegType')" :key="index" :value="item.value"
                  :label="`${item.name} (${item.code}) [${item.value}] `" />

              </el-select>

            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="4" class="mb10" v-if="showAdvanceQueryUI">
            <el-form-item label="单位">
              <el-input v-model="queryParams.unit" clearable="" placeholder="请输入单位" />

            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="4" class="mb10" v-if="showAdvanceQueryUI">
            <el-form-item label="读写属性">
              <el-select clearable="" v-model="queryParams.readWrite" placeholder="请选择读写属性">
                <el-option v-for="(item, index) in dl('ReadWrite')" :key="index" :value="item.value"
                  :label="`${item.name} (${item.code}) [${item.value}] `" />

              </el-select>

            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="4" class="mb10" v-if="showAdvanceQueryUI">
            <el-form-item label="精确几位">
              <el-select clearable="" v-model="queryParams.precisionEnum" placeholder="请选择精确几位">
                <el-option v-for="(item, index) in dl('PrecisionEnum')" :key="index" :value="item.value"
                  :label="`${item.name} (${item.code}) [${item.value}] `" />

              </el-select>

            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="4" class="mb10">
            <el-form-item>
              <el-button-group style="display: flex; align-items: center;">
                <el-button type="primary" icon="ele-Search" @click="handleQuery"
                  v-auth="'deviceSlaveTemplatePoints:page'"> 查询 </el-button>
                <el-button type="primary" style="margin-left:5px;" icon="ele-Plus"
                  @click="openAddDeviceSlaveTemplatePoints" v-auth="'deviceSlaveTemplatePoints:add'"> 新增 </el-button>
                <el-button type="danger" style="margin-left:5px;" icon="ele-Delete"
                  @click="deleteDeviceSlaveTemplatePointsBySlaveId" v-auth="'deviceSlaveTemplatePoints:delete'"> 清空所有点
                </el-button>
                <el-button type="primary" style="margin-left:5px;" icon="ele-Plus" @click="openUploadDialog"
                  v-auth="'deviceSlaveTemplatePoints:add'"> 变量导入 </el-button>
                <el-button type="primary" style="margin-left:5px;" icon="ele-Download"
                  @click="exportDeviceSlaveTemplatePoints" v-auth="'deviceSlaveTemplatePoints:add'"> 变量导出 </el-button>
                  <el-button type="primary" style="margin-left:5px;" icon="ele-Download"
                  @click="downloadImportFileTemplate" > 模板下载 </el-button>
              </el-button-group>
            </el-form-item>

          </el-col>
        </el-row>
      </el-form>
    </el-card>
    <el-card class="full-table" shadow="hover" style="margin-top: 5px">
      <el-table :data="tableData" style="width: 100%" v-loading="loading" tooltip-effect="light" row-key="id"
        @sort-change="sortChange">
        <el-table-column type="index" label="序号" width="55" align="center" />
        <el-table-column prop="pointName" label="变量名字" show-overflow-tooltip="" width="200" />
        <!-- <el-table-column prop="dataType" label="数据类型" show-overflow-tooltip="">
          <template #default="scope">
            <el-tag :type="dv('DataType', scope.row.dataType)?.tagType"> {{ dv('DataType',
              scope.row.dataType)?.name}}</el-tag>
          </template>
</el-table-column> -->
        <!-- <el-table-column prop="len" label="长度" show-overflow-tooltip="" /> -->
        <el-table-column prop="reg" label="寄存器地址" show-overflow-tooltip="" />
        <!-- <el-table-column prop="regType" label="寄存器类型" show-overflow-tooltip="">
          <template #default="scope">
            <el-tag :type="dv('RegType', scope.row.regType)?.tagType"> {{ dv('RegType',
              scope.row.regType)?.name}}</el-tag>
          </template>
        </el-table-column> -->
        <!-- <el-table-column prop="varType" label="变量类型" show-overflow-tooltip="" /> -->
        <el-table-column prop="unit" label="单位" show-overflow-tooltip="" />
        <el-table-column prop="readWrite" label="读写属性" show-overflow-tooltip="">
          <template #default="scope">
            <el-tag :type="dv('ReadWrite', scope.row.readWrite)?.tagType"> {{ dv('ReadWrite',
              scope.row.readWrite)?.name }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="store" label="存储方式" show-overflow-tooltip="">
          <template #default="scope">
            <el-tag :type="dv('StoreType', scope.row.store)?.tagType"> {{ dv('StoreType',
              scope.row.store)?.name }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="cycle" label="采集频率" show-overflow-tooltip="">
          <template #default="scope">
            <el-tag :type="dv('CycleType', scope.row.cycle)?.tagType"> {{ dv('CycleType',
              scope.row.cycle)?.name }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="precisionEnum" label="小数位" show-overflow-tooltip="">
          <template #default="scope">
            <el-tag :type="dv('PrecisionEnum', scope.row.precisionEnum)?.tagType"> {{ dv('PrecisionEnum',
              scope.row.precisionEnum)?.name }}</el-tag>
          </template>
        </el-table-column>
        <!-- <el-table-column prop="formula" label="采集公式"   /> -->
        <el-table-column prop="formula">
          <template #header>
            <el-tooltip class="item" effect="dark" content="设备上行数据经采集公式计算后显示 。

公式中的%s为占位符，是固定字段。

如：

加：%s+10

减：%s-10

乘：%s*10

除：%s/10

余数：%s%10" placement="top">
              <span>采集公式</span>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column prop="reFormula" label="控制公式" show-overflow-tooltip="" />
        <el-table-column label="操作" width="220" align="center" fixed="right" show-overflow-tooltip=""
          v-if="auth('deviceSlaveTemplatePoints:update') || auth('deviceSlaveTemplatePoints:delete')">
          <template #default="scope">
            <el-button icon="ele-Edit" size="small" text="" type="primary"
              @click="openEditDeviceSlaveTemplatePoints(scope.row)" v-auth="'deviceSlaveTemplatePoints:update'"> 编辑
            </el-button>
            <el-button icon="ele-Edit" size="small" text="" type="primary"
              @click="openPointTrigger(scope.row.id,scope.row.pointName)" v-auth="'deviceSlaveTemplatePoints:update'"> 触发器
            </el-button>
            <el-button icon="ele-Delete" size="small" text="" type="primary"
              @click="delDeviceSlaveTemplatePoints(scope.row)" v-auth="'deviceSlaveTemplatePoints:delete'"> 删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination v-model:currentPage="tableParams.page" v-model:page-size="tableParams.pageSize"
        :total="tableParams.total" :page-sizes="[10, 20, 50, 100, 200, 500]" size="small" background=""
        @size-change="handleSizeChange" @current-change="handleCurrentChange"
        layout="total, sizes, prev, pager, next, jumper" />
      <printDialog ref="printDialogRef" :title="printDeviceSlaveTemplatePointsTitle" @reloadTable="handleQuery" />
      <editDialog ref="editDialogRef" :title="editDeviceSlaveTemplatePointsTitle" @reloadTable="handleQuery" />
      <el-dialog v-model="state.dialogUploadVisible" :lock-scroll="false" draggable width="400px">
        <template #header>
          <div style="color: #fff">
            <el-icon size="16" style="margin-right: 3px; display: inline; vertical-align: middle"> <ele-UploadFilled />
            </el-icon>
            <span> 上传文件 </span>
          </div>
        </template>
        <div>

          <el-upload ref="uploadRef" drag :auto-upload="false" :limit="1" :file-list="state.fileList" action=""
            :on-change="handleChange" accept=".jpg,.png,.bmp,.gif,.txt,.pdf,.xlsx,.docx">
            <el-icon class="el-icon--upload">
              <ele-UploadFilled />
            </el-icon>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
            <template #tip>
              <div class="el-upload__tip">请上传大小不超过 10MB 的文件</div>
              <div class="el-upload__tip">只能上传1个文件</div>
            </template>
          </el-upload>
          <div v-html="uploadMessage"></div>
        </div>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="state.dialogUploadVisible = false">取消</el-button>
            <el-button type="primary" @click="uploadFile">确定</el-button>
          </span>
        </template>
      </el-dialog>
      <triggerEditDialog
        ref="triggerEditDialogRef"
        title="模板触发器"
        @reloadTable="handleQuery"
      />
    </el-card>
    
  </div>
    
</template>

<script lang="ts" setup="" name="deviceSlaveTemplatePoints">
import { ref, onMounted, onUpdated, reactive } from "vue";
import { ElMessageBox, ElMessage } from "element-plus";
import { auth } from '/@/utils/authFunction';

import { getDictDataItem as di, getDictDataList as dl } from '/@/utils/dict-utils';
import { getDictLabelByVal as dv } from '/@/utils/dict-utils';
import { formatDate } from '/@/utils/formatTime';


import printDialog from '/@/views/system/print/component/hiprint/preview.vue'
import editDialog from '/@/views//Device/Template/deviceSlaveTemplatePoints/component/editDialog.vue'
import triggerEditDialog from '/@/views/Device/deiviceTemplateTrigger/component/editDialog.vue'

import { pageDeviceSlaveTemplatePoints, deleteDeviceSlaveTemplatePoints, importDeviceSlaveTemplatePoints, deleteByDeviceSlaveTemplateId,getImportFileTemplate,exportPoints } from '/@/api//Device/Template/deviceSlaveTemplatePoints';
import { getDeviceSlaveTemplateDeviceSlaveTemplateIdDropdown } from '/@/api//Device/Template/deviceSlaveTemplatePoints';
import { getAPI } from '/@/utils/axios-utils';
import { SysEnumApi } from '/@/api-services/api';
import commonFunction from '/@/utils/commonFunction';
import { SysFile } from "/@/api-services";
import { downloadByUrl } from '/@/utils/download';

// 定义 props
const props = defineProps({
  deviceSlaveTemplateId: {
    type: String,
    default: null
  }
});
const uploadMessage = ref("");
const showHasPropsAdvanceQueryUI = ref(true);
const showAdvanceQueryUI = ref(false);
const printDialogRef = ref();
const editDialogRef = ref();
const triggerEditDialogRef = ref();
const loading = ref(false);
const tableData = ref<any>([]);
const queryParams = ref<any>({});
const state = reactive({
  dialogUploadVisible: false,
  fileType: "",
  isPublic: false,
  fileList: [] as any,
  deviceSlaveTemplateId: "",
});
const tableParams = ref({
  page: 1,
  pageSize: 10,
  field: 'createTime', // 默认的排序字段
  order: 'descending', // 排序方向
  descstr: 'descending', // 降序排序的关键字符
  total: 0 as any,
});

const printDeviceSlaveTemplatePointsTitle = ref("");
const editDeviceSlaveTemplatePointsTitle = ref("");

// 改变高级查询的控件显示状态
const changeAdvanceQueryUI = () => {
  showAdvanceQueryUI.value = !showAdvanceQueryUI.value;
}

// 查询操作
const handleQuery = async () => {
  console.log("id:" + props.deviceSlaveTemplateId)
  queryParams.value.deviceSlaveTemplateId = props.deviceSlaveTemplateId;
  loading.value = true;
  var res = await pageDeviceSlaveTemplatePoints(Object.assign(queryParams.value, tableParams.value));
  tableData.value = res.data.result?.items ?? [];
  tableParams.value.total = res.data.result?.total;
  loading.value = false;
};

// 列排序
const sortChange = async (column: any) => {
  tableParams.value.field = column.prop;
  tableParams.value.order = column.order;
  await handleQuery();
};

// 打开新增页面
const openAddDeviceSlaveTemplatePoints = () => {
  editDeviceSlaveTemplatePointsTitle.value = '添加从机变量';
  if (props.deviceSlaveTemplateId) {
    editDialogRef.value.openDialog({ deviceSlaveTemplateId: props.deviceSlaveTemplateId + "" });
  } else {
    editDialogRef.value.openDialog({});
  }


};

// 打开打印页面
const openPrintDeviceSlaveTemplatePoints = async (row: any) => {
  printDeviceSlaveTemplatePointsTitle.value = '打印从机变量';
}

// 打开编辑页面
const openEditDeviceSlaveTemplatePoints = (row: any) => {
  editDeviceSlaveTemplatePointsTitle.value = '编辑从机变量';
  editDialogRef.value.openDialog(row);
};
const openPointTrigger = (id:any,pointName:any) => {
  
  triggerEditDialogRef.value.openDialogByPointId(id,pointName);
};

// 删除
const delDeviceSlaveTemplatePoints = (row: any) => {
  ElMessageBox.confirm(`确定要删除吗?`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      await deleteDeviceSlaveTemplatePoints(row);
      handleQuery();
      ElMessage.success("删除成功");
    })
    .catch(() => { });
};

// 改变页面容量
const handleSizeChange = (val: number) => {
  tableParams.value.pageSize = val;
  handleQuery();
};

// 改变页码序号
const handleCurrentChange = (val: number) => {
  tableParams.value.page = val;
  handleQuery();
};
// 删除模板下的所有变量
const deleteDeviceSlaveTemplatePointsBySlaveId = () => {

  //询问是否要删除
  ElMessageBox.confirm(`确定要删除吗?`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      var id = props.deviceSlaveTemplateId;
      await deleteByDeviceSlaveTemplateId({ "id": id });
      handleQuery();
      ElMessage.success("删除成功");
    })
    .catch(() => { });

};
const deviceSlaveTemplateDeviceSlaveTemplateIdDropdownList = ref<any>([]);
const getDeviceSlaveTemplateDeviceSlaveTemplateIdDropdownList = async () => {
  let list = await getDeviceSlaveTemplateDeviceSlaveTemplateIdDropdown();
  deviceSlaveTemplateDeviceSlaveTemplateIdDropdownList.value = list.data.result ?? [];
};

onMounted(() => {
  console.log('页面加载时:' + props.deviceSlaveTemplateId);
  if (props.deviceSlaveTemplateId) {
    queryParams.value.deviceSlaveTemplateId = props.deviceSlaveTemplateId;
    showHasPropsAdvanceQueryUI.value = false;
  }
  getDeviceSlaveTemplateDeviceSlaveTemplateIdDropdownList();
  handleQuery();

});
onUpdated(() => {
  console.log('onUpdated页面更新时:' + props.deviceSlaveTemplateId);
  // if (props.deviceSlaveTemplateId) {
  //   queryParams.value.deviceSlaveTemplateId = props.deviceSlaveTemplateId;
  //   showHasPropsAdvanceQueryUI.value = false;
  // }
  // getDeviceSlaveTemplateDeviceSlaveTemplateIdDropdownList();
  // handleQuery();
});
const uploadFile = async () => {
  state.deviceSlaveTemplateId = props.deviceSlaveTemplateId;
  //通过state组织一个
  const formData = new FormData();

  formData.append('file', state.fileList[0].raw);
  formData.append('deviceSlaveTemplateId', props.deviceSlaveTemplateId);
  var re = await importDeviceSlaveTemplatePoints(formData);
  console.log(re)
  if (re.data.result.isSuccess) {
    ElMessage.success("导入成功");
    state.dialogUploadVisible = false;
    handleQuery();

  } else {
    //messagebox展示错误的信息
    const errorMessage = re.data.result.messages.join('<br />');
    uploadMessage.value=errorMessage;
  }
}
const downloadImportFileTemplate = async () => {
  var re = await getImportFileTemplate();
  console.log(re)
  var result = re.data.result as SysFile;
  // 获取文件地址
 var url = getFileUrl(result);
 downloadByUrl({ url: url });
 
}

const getFileUrl = (row: SysFile): string => {
	if (row.bucketName == 'Local') {
		return `/${row.filePath}/${row.id}${row.suffix}`;
	} else {
		return row.url!;
	}
};
// 通过onChanne方法获得文件列表
const handleChange = (file: any, fileList: []) => {
  state.fileList = fileList;
};

// 打开上传页面
const openUploadDialog = () => {
  state.fileList = [];
  state.dialogUploadVisible = true;
  state.isPublic = false;
  uploadMessage.value="";
};

// 导出
const exportDeviceSlaveTemplatePoints = async () => {
  try {
    const re = await exportPoints(props.deviceSlaveTemplateId);
    console.log(re);
    const blob = re.data;
    const contentDisposition = re.headers['content-disposition'];
    let fileName = 'DeviceSlaveTemplatePoints.xlsx';
    if (contentDisposition) {
      const matches = contentDisposition.match(/filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/);
      if (matches != null && matches[1]) {
        fileName = matches[1].replace(/['"]/g, '');
      }
    }
    const url = window.URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    link.setAttribute('download', fileName); // 设置下载文件名
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    window.URL.revokeObjectURL(url); // 释放内存
  } catch (error) {
    ElMessage.error('导出失败');
  }
  //
};
</script>
<style scoped>
:deep(.el-input),
:deep(.el-select),
:deep(.el-input-number) {
  width: 100%;
}
</style>
